#include "stm32f10x.h"                  // Device header

uint16_t Count;

/**
  * @brief		初始化对射红外计数传感器，注意GPIO和AFIO的时钟开启
  * @parm		无
  * @retval		无
  */
void CounterSonsor_Init(void)
{
	//初始化GPIO
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);		//开启时钟
	GPIO_InitTypeDef GPIO_InitStructure;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;				//上拉输入
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_14;					//B14
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;	
	GPIO_Init(GPIOB, &GPIO_InitStructure);
	
	//初始化AFIO	函数定义在gpio.h
	//将指定GPIO的指定引脚映射为中断引脚
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);		//开启时钟，外部中断必须开启AFIO时钟
	GPIO_EXTILineConfig(GPIO_PortSourceGPIOB, GPIO_PinSource14);
	
	//初始化EXTI	函数定义在exti.h
	EXTI_InitTypeDef EXTI_InitStructure;
	EXTI_InitStructure.EXTI_Line = EXTI_Line14;				//中断引脚	
	EXTI_InitStructure.EXTI_LineCmd = ENABLE;				//使能开关	
	EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;		//中断触发
	EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling;	//下降沿触发
	EXTI_Init(&EXTI_InitStructure);
	
	//中断优先级分组	函数定义在misc.h
	//抢占分组2，响应分组2
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
	
	//初始化NVIC	函数定义在misc.h
	NVIC_InitTypeDef NVIC_InitStructure;
	NVIC_InitStructure.NVIC_IRQChannel = EXTI15_10_IRQn;		//IRQ通道
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;				//使能开关
	//因为中断优先级分组为2，即各自2位，表示范围0~3
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;	//抢占优先级1
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;			//响应优先级1
	NVIC_Init(&NVIC_InitStructure);
}

/**
  * @brief		获取计数
  * @parm		无
  * @retval		计数器数值
  */
uint16_t CounterSensor_GetCount(void)
{
	return Count;
}


//中断处理函数		定义在startup...h启动文件
void EXTI15_10_IRQHandler(void)
{
	//10~15中断都触发该函数，需要判断一下
	if(EXTI_GetITStatus(EXTI_Line14) == SET)//SET == 1
	{
		/*如果出现数据乱跳的现象，可再次判断引脚电平，以避免抖动*/
		if (GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_14) == 0)
			Count++;
		//还需要清除中断标志位
		EXTI_ClearFlag(EXTI_Line14);
	}
}


